<style lang='scss'>
#base-info {
  .convert-dialog > .el-dialog {
    width: 1700px;
  }

  .el-textarea.is-disabled .el-textarea__inner,
  .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }

  .form-table {
    .el-table__fixed-header-wrapper > table > thead > tr > th > .cell,
    .el-table__header-wrapper > table > thead > tr > th > .cell {
      padding: 10px 0;
      text-align: center;
      font-weight: bold;
    }
  }

  .el-table-column--selection > .cell {
    text-align: center;
  }
  .part {
    border: 1px solid #ccc;
    margin-bottom: 20px;
    background-color: #fff;
    .table-title {
      cursor: pointer;
      padding: 10px;
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
    }
  }
  .mt15 {
    margin-top: 15px;
  }

  .button-box {
    text-align: center;
    padding: 20px;
    background-color: #fff;
  }
}
</style>
<template>
  <div id="base-info">
    <Box>

    <SearchContainer>
      <el-form :inline="true" label-width="110px" :model="searchForm" class="query-form mb20">
        <el-form-item label="名称" prop="path">
          <el-input v-model="searchForm.name" placeholder="请输入名称" auto-complete="off"></el-input>
        </el-form-item>
        <div class="tc mb20">
          <el-button type="primary" size="small" icon="el-icon-search" @click="onSearch()">查询</el-button>
          <el-button type="success" size="small" icon="el-icon-plus" @click="addItem({key:'list'})">新增</el-button>
          <el-button type="warning" size="small" icon="el-icon-refresh" @click="searchForm={}">重置</el-button>
        </div>
      </el-form>
    </SearchContainer>

    
    <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyForm" :label-position="'' | LABEL_POSITION">
      <el-table
        v-loading="regionLoading"
        element-loading-spinner="el-icon-loading"
        :data="modifyForm.list"
        border
        class="form-table"
        :max-height="maxHeight"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column v-if="type !='view'" type="selection" width="55" class="tc"></el-table-column> -->

        <el-table-column label="name" min-width="200">
          <template slot-scope="scope">
            <el-form-item :prop=" 'list.' + scope.$index + '.name' " :rules="modifyFormRules.name" class="mt15" v-if="scope.row.editStatus">
              <el-input
                type="textarea"
                :disabled=" !scope.row.editType "
                :autosize="{ minRows: 1, maxRows: 1}"
                v-model="scope.row.name"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
            <span v-else :title="scope.row.name">{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="targetObject" min-width="200">
          <template slot-scope="scope">
            <el-form-item :prop=" 'list.'  + scope.$index + '.content.targetObject' " :rules="modifyFormRules.targetObject" class="mt15" v-if="scope.row.editStatus">
              <el-input
                type="textarea"
                :readonly="type == 'view'"
                :autosize="{ minRows: 1, maxRows: 1}"
                v-model="scope.row.content.targetObject"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
            <span v-else :title="scope.row.content.targetObject">{{scope.row.content.targetObject}}</span>
          </template>
        </el-table-column>
        <el-table-column label="beanMapping" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="OpenDialog(scope.row)">查看/编辑</el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-col>
              <el-button type="text" @click="copyData(scope.row)">复制</el-button>
              <el-button type="text" @click="onSubmitForm(scope.row)">{{type == 'view' ? '编辑' : '保存'}}</el-button>
              <el-button v-if="!scope.row.editType" type="text" @click="onDelRecord({index:scope.$index,row:scope.row})">删除</el-button>
              <el-button v-else type="text" @click="delItem({key:'list',index:scope.$index,row:scope.row})">取消</el-button>
            </el-col>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-row v-if="type != 'view'">
        <el-col :span="24" class="button-box">
          <el-button type="success" @click="addItem({key:'list'})">新增Item</el-button>
          <el-button :disabled="selection.length == 0" type="warning" @click="delItem({key:'list',findKey:'creator'})">删除Item</el-button>
        </el-col>
      </el-row>-->
    </el-form>
    <el-pagination
      v-if="this.pager.total > 0 "
      :page-sizes="pagination.pageSizes"
      :page-size="pager.pageSize"
      :layout="pagination.layout"
      :total="pager.total"
      :current-page="pager.pageIndex"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <!-- <el-row>
      <el-col :span="24" class="button-box">
         <el-button type="primary" @click="onSubmitForm">{{type == 'view' ? '编辑' : '保存'}}</el-button>
        <el-button type="danger" v-if=" type != 'view' " @click="onSubmitForm">删除</el-button>
        <el-button @click="modifyDialogVisible = false;">返回</el-button>
      </el-col>
    </el-row>-->
    <el-dialog
      top="2vh"
      :width="'' | DIALOG_WIDTH"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="viewDialogVisible"
      class="dialog-custom-box"
      v-dialogDrag
      ref="dialog__wrapper"
    >
      <FormatSub ref="formatSub" :rowForm.sync="rowForm" @closeDialog="closeDialog" @onSubmitSubForm="onSubmitSubForm"/>
      <div class="line" v-dialogDragWidth="$refs.dialog__wrapper"></div>
    </el-dialog>
    </Box>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import SearchContainer from "src/components/common/SearchContainer";
import storage from "src/utils/storage";
import { sendReq, tableExportExcel, isJSON ,GetQueryString} from "src/utils/tools";
const formatItem = {
  content: {
    beanMapping: [{
      srcField: '',
      type: '',
      targetField: '',
      el: '',
      validate: '',
    }],
    targetObject: '',
  },
  name: '',
  editType: 'add',
  editStatus:true
};

export default {
  data() {
    const pagePermissionsMenu = storage.get("pagePermissionsMenu")
      ? storage.get("pagePermissionsMenu")
      : {};

    const inputWarning = (msg) => {
      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change",
        }
      ];
    };
    let checkEmpty = (obj) => {
      return (rule, value, callback) => {
        if (value != undefined) {
          return callback(new Error(obj.msg));
        } else {
          callback();
        }
      };
    };
    let validateEmpty = (obj) => ([{ required: true, validator: checkEmpty(obj), trigger: 'blur' }]);

    return {
      searchForm: {},
      zkConfigTypeEnum: '',
      type: 'edit',
      title: 'beanMappingForm',
      viewDialogVisible: false,
      rowForm: [],
      maxHeight: document.documentElement.clientHeight - 90 - 110 - 75,
      modifyForm: {

        list: [JSON.parse(JSON.stringify(formatItem))],
      },
      modifyFormRules: {
        name: inputWarning('请输入name'),
        targetObject: inputWarning('请输入targetObject'),
      },
      selection: [],
      pager: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
      }
    };
  },
  components: {
    FormatSub: (resolve) => {
      require(['./formatSub.vue'], resolve)
    }
  },
  computed: {
    ...mapGetters(["pagination", "regionLoading", 'valveOpts'])
  },
  watch: {
    $route:function(val){
      this.onSearch()
    }
  },
  mounted() {
    this.onSearch();
    this.changeCollapseState(false);
    
  },
  methods: {
    ...mapActions(["changeCollapseState"]),
    onSubmitSubForm(row) {
      this.closeDialog();
      this.onSubmitForm(row);
    },
    closeDialog() {
      this.viewDialogVisible = false;
    },
    onSearch() {
      
      let obj = {};
      if (this.$route.name == '/router库/router格转') {
        if (this.$route.query.convertName) {
          this.searchForm.name = this.$route.query.convertName;
        }
        obj = {
          url: '/config/getRouterConvertList',
          params: { productCode: this.$route.params.productCode, nodeName: this.searchForm.name },
        };
      } else if (this.$route.name == '/handler库/格转' || this.$route.name == '/handler库/mock') {
        obj = {
          url: this.$route.name == '/handler库/格转' ? '/config/getHandlerConvertList' : '/config/getHandlerMockList',
          params: { nodeName: this.searchForm.name },
        };
      }
      let pages = {
        pageNum: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
      } 
      sendReq({
        url: obj.url,
        params: {...obj.params,...pages},
        showLoading: true,
        cb: (returnData) => {
          if (returnData.data ) {
            returnData.data.forEach(e =>{
              e.editStatus = false
            })
            this.zkConfigTypeEnum = returnData.zkConfigTypeEnum;
            this.modifyForm.list = returnData.data;
            this.pager.total = returnData.totalRecord;
            if (this.$route.query.addName) {
              this.modifyForm.list.unshift({
                content: {
                  beanMapping: [{
                    srcField: '',
                    type: '',
                    targetField: '',
                    el: '',
                    validate: '',
                  }],
                  targetObject: '',
                },
                name: this.$route.query.addName,
              });
              this.$route.query.addName = '';
            }
          }
        }
      })
    },
    OpenDialog(row) {
      this.rowForm = Object.assign({}, JSON.parse(JSON.stringify(row)));
      this.viewDialogVisible = true;
    },
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    addItem(obj) {
      this.modifyForm[obj.key].unshift(JSON.parse(JSON.stringify(formatItem)));
    },
    delItem(obj) {
      let msg = obj.row.editType ? '取消' : '删除';
      this.$confirm(`确定要${msg}这条记录吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.modifyForm[obj.key].splice(obj.index, 1);
      })
    },
    //新增&&编辑保存
    onSubmitForm(row) {
      let args = {};
      args = {
        url: row.editType ? '/config/addNode' : '/config/updateNode',
        params: {
          productCode: this.$route.params.productCode,
          name: row.name,
          content: row.content,
          zkConfigTypeEnum: this.zkConfigTypeEnum,
        }
      }
      sendReq({
        url: args.url,
        params: args.params,
        note: true,
        cb: (data) => {
          this.onSearch();
        }
      })
    },
    // 删除
    onDelRecord(params) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        sendReq({
          url: '/config/deleteNode',
          params: { path: params.row.path },
          note: true,
          cb: (data) => {
            this.onSearch();
          }
        })
      })
    },
    copyData(data){
      let temp = JSON.parse(JSON.stringify(data))
      temp.editType = true;
      temp.name = temp.name + ".copy";
      //temp.content.targetObject = temp.content.targetObject + ".copy";
      temp.editStatus = true;
      this.modifyForm.list.unshift(temp) 
    },
    handleSizeChange(pageSize) {
      this.pager.pageSize = pageSize;
      this.onSearch();
    },
    handleCurrentChange(pageIndex) {
      this.pager.pageIndex = pageIndex;
      this.onSearch();
    }
  }
};
</script>
